package com.simple.card.aspect;

import com.simple.card.Utils.IAuth;
import com.simple.card.annotation.SignCheck;
import com.simple.card.enums.ResultEnum;
import com.simple.card.exception.CreditException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
public class SignAuthAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("execution(public * com.simple.card.controller.*.*(..)) && @annotation(signCheck)")
    public Object doVerify(ProceedingJoinPoint point, SignCheck signCheck) {
        try {
            boolean sign = signCheck.sign();
            if(sign){
                //获取header头
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
                String signValue = request.getHeader("Sign");
                String timestamp = request.getHeader("Time");
                if(StringUtils.isEmpty(signValue) || StringUtils.isEmpty(timestamp)) {
                    throw new CreditException(ResultEnum.SIGN_PARAM_CANNOT_EMPTY);
                }
                IAuth iAuth = new IAuth();
                if(!iAuth.checkSignPass(signValue,timestamp, redisTemplate)){
                    throw new CreditException(ResultEnum.SIGN_ERROR);
                }
                redisTemplate.opsForValue().set(signValue,"1",310, TimeUnit.SECONDS);
            }
            return point.proceed();
        } catch (Throwable throwable) {
            throw new CreditException(((CreditException) throwable).getCode(),throwable.getMessage());
        }
    }
}
